package org.csu.newpetstoreback.controller.front;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.csu.newpetstoreback.config.AliPayConfig;
import org.csu.newpetstoreback.vo.OrderPayVO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
public class AliPayController {

    @PostMapping("/alipay/pay")
    @ResponseBody
    public static String pay(@RequestBody OrderPayVO orderPayVO) throws Exception {
        //获取要向支付宝支付的参数,由页面传过来
        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = orderPayVO.getOrderId();
        //付款金额，必填
        String total_amount = orderPayVO.getTotalPrice();
        //订单名称，必填
        String subject = orderPayVO.getOrderName();
        //商品描述，可空
        String body = orderPayVO.getOrderDate();//实际是下单时间

        System.out.println("商户订单号:" + out_trade_no);
        System.out.println("付款金额:" + total_amount);
        System.out.println("订单名称:" + subject);
        System.out.println("商品描述:" + body);

        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AliPayConfig.GATEWAY_URL,
                AliPayConfig.APP_ID, AliPayConfig.MERCHANT_PRIVATE_KEY,
                "json", AliPayConfig.CHARSET, AliPayConfig.ALIPAY_PUBLIC_KEY, AliPayConfig.SIGN_TYPE);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AliPayConfig.RETURN_URL);  //设置同步回调通知
        alipayRequest.setNotifyUrl(AliPayConfig.NOTIFY_URL);  //设置异步回调通知
        //设置支付参数
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求
        String result = null;

        try {
            result = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println("Str：" + result);

        return result;
    }

    @GetMapping("/alipay/notify")
    @ResponseBody
    public String pay_notify(Map requestParams) {

        System.out.println("支付完成进入异步通知"+requestParams.toString());
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();

        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        try {
            boolean flag = AlipaySignature.rsaCheckV1(params, AliPayConfig.ALIPAY_PUBLIC_KEY, AliPayConfig.CHARSET, AliPayConfig.SIGN_TYPE);
            if(flag){
                if("TRADE_SUCCESS".equals(params.get("trade_status"))){
                    //付款金额
                    String amount = params.get("buyer_pay_amount");
                    //商户订单号
                    String out_trade_no = params.get("out_trade_no");
                    //支付宝交易号
                    String trade_no = params.get("trade_no");
                    //附加数据
                    String passback_params = URLDecoder.decode(params.get("passback_params"));

                    return "alipay/success";
                }else {
                    //支付失败不处理业务逻辑
                    return "alipay/failure";
                }
            }else {
                //签名验证失败不处理业务逻辑
                return "alipay/failure";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return "alipay/failure";
        }
    }

    @GetMapping("/alipay/return")
    @ResponseBody
    public String pay_return(Map requestParams) {
        System.out.println("支付完成进入同步通知"+requestParams.toString());
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();

        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        try {
            boolean signVerified = AlipaySignature.rsaCheckV1(params, AliPayConfig.ALIPAY_PUBLIC_KEY, AliPayConfig.CHARSET, AliPayConfig.SIGN_TYPE);
            if(signVerified){
                //跳转支付成功界面
                return "alipay/success";

            }else {
                //跳转支付失败界面
                return "alipay/failure";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return "alipay/failure";
        }
    }

}
